<?php
namespace app\api\controller;

class Coze1231 extends Base
{
    //对接扣子平台

    //访问令牌
    protected $token = 'pat_yce69DozL0bMvx8B6PqSAEs834migHP0EgCbnvMBgErWp8k5fgUs9zR7odO9iVNt';
    //智能体ID
    protected $bot_id = '7452915373378781219';

    //实例化
    public function obj(){
        return new \app\api\model\Coze();
    }

    //headers
    public function headers(){
        return [
            'Authorization: Bearer ' . $this->token,
            'Content-Type: application/json',
        ];
    }

    /**
     * 对话流程：
     * 发起会话，拿到会话ID，https://api.coze.cn/v3/chat
     * 获取智能体回复，通过会话ID，https://api.coze.cn/v3/chat/message/list
     */

    /**
     * 创建会话
     * POST https://api.coze.cn/v1/conversation/create
     */
    public function hhOne()
    {
        $pas = $this->request->param();
        $imei = isset($pas['imei'])&&$pas['imei'] ? $pas['imei'] : '';
        if (!$imei) {
            return $this->toJson(-2, '没有机器编号');
        }
        $hh = $this->obj()->hhOne($imei);
        if (!$hh) {
            $httpUrl = 'https://api.coze.cn/v1/conversation/create';
            $res = $this->cozeCurl($httpUrl, 2);
            if ($res['code'] < 0) {
                return $this->toJson(-2, $res['msg']);
            }
            $res = $res['data'];
            if ($res['code'] < 0) {
                return $this->toJson(-2, $res['msg']);
            }
            $hh_id = $res['data']['id'];
            $hhOne = $this->obj()->hhAdd($hh_id, $imei);
            if (!$hhOne) {
                return $this->toJson(-2,'fail');
            }
        } else {
            $hh_id = $hh['hh_id'];
        }
        return $this->toJson(0, '', $hh_id);
    }

    /**
     * 用户发起会话
     * POST https://api.coze.cn/v3/chat
     */
    public function hhRun()
    {
        $pas = $this->request->param();
        $cnt = isset($pas['cnt'])&&$pas['cnt'] ? $pas['cnt'] : '';
        $hh_id = isset($pas['hh_id'])&&$pas['hh_id'] ? $pas['hh_id'] : '7453276182402957312';
        if (!$cnt) {
            return $this->toJson(-2, '没有内容');
        }
        $httpUrl = 'https://api.coze.cn/v3/chat?conversation_id='.$hh_id;
        $httpData = json_encode([
            'bot_id' => $this->bot_id,
            'user_id' => '111',
            'stream' => false,
            'auto_save_history' => true,
            'additional_messages' => [
                [
                    'role' => 'user',
                    'content_type' => 'text',
                    'content' => $cnt,
                ],
            ],
        ]);
        $res = $this->cozeCurl($httpUrl, 2, $httpData);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

//    /**
//     * 发消息
//     * POST https://api.coze.cn/v1/conversation/message/create
//     */
//    public function userMsg()
//    {
//        $pas = $this->request->param();
//        $cnt = isset($pas['cnt'])&&$pas['cnt'] ? $pas['cnt'] : '';
////        $chat_id = isset($pas['chat_id'])&&$pas['chat_id'] ? $pas['chat_id'] : '7454397026357477428';
//        if (!$cnt) {
//            return $this->toJson(-2, '没有内容');
//        }
//        $httpUrl = 'https://api.coze.cn/v1/conversation/message/create?conversation_id=7453276182402957312';
//        $httpData = json_encode([
//            'role' => 'user',
//            'content' => $cnt,
//            'content_type' => 'text',
//        ]);
//        $res = $this->cozeCurl($httpUrl, 2, $httpData);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        $res = $res['data'];
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        return $this->toJson(0, '', $res['data']);
//    }

    /**
     * 智能体回复
     * GET https://api.coze.cn/v3/chat/message/list
     */
    public function botMsg()
    {
        $pas = $this->request->param();
        $chat_id = isset($pas['chat_id'])&&$pas['chat_id'] ? $pas['chat_id'] : '7454397026357477428';
        if (!$chat_id) {
            return $this->toJson(-2, '没有对话ID');
        }
        $httpUrl = 'https://api.coze.cn/v3/chat/message/list?conversation_id=7453276182402957312&chat_id='.$chat_id;
        $res = $this->cozeCurl($httpUrl, 1);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

//    /**
//     * 消息列表
//     * POST https://api.coze.cn/v1/conversation/message/list
//     */
//    public function msgList()
//    {
//        $pas = $this->request->param();
//        $chat_id = isset($pas['chat_id'])&&$pas['chat_id'] ? $pas['chat_id'] : '7454397026357477428';
//        $httpUrl = 'https://api.coze.cn/v1/conversation/message/list?conversation_id=7453276182402957312';
//        $httpData = json_encode([
//            'chat_id' => $chat_id,
//        ]);
//        $res = $this->cozeCurl($httpUrl, 2, $httpData);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        $res = $res['data'];
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        return $this->toJson(0, '', $res['data']);
//    }
//
//    /**
//     * 消息详情
//     * GET  https://api.coze.cn/v1/conversation/message/retrieve
//     */
//    public function msgOne()
//    {
//        $pas = $this->request->param();
//        $message_id = isset($pas['chat_id'])&&$pas['message_id'] ? $pas['message_id'] : '7454408117393063990';
//        $httpUrl = 'https://api.coze.cn/v1/conversation/message/retrieve?conversation_id=7453276182402957312&message_id='.$message_id;
//        $res = $this->cozeCurl($httpUrl);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        $res = $res['data'];
//        return $this->toJson(0, '', $res);
//    }

//    /**
//     * 音色列表
//     * GET https://api.coze.cn/v1/audio/voices
//     */
//    public function voiceList()
//    {
//        $httpUrl = 'https://api.coze.cn/v1/audio/voices';
//        $res = $this->cozeCurl($httpUrl);
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        $res = $res['data'];
//        if ($res['code'] < 0) {
//            return $this->toJson(-2, $res['msg']);
//        }
//        return $this->toJson(0, '', $res['data']);
//    }
//
//    /**
//     * 语音合成
//     * POST https://api.coze.cn/v1/audio/speech
//     */
//    public function yuyin()
//    {
//        $httpUrl = 'https://api.coze.cn/v1/audio/speech';
//        $httpData = json_encode([
//            'input' => '天气怎么样',
//            'voice_id' => '2',
//            'response_format' => 'mp3',
//        ]);
//        $res = $this->cozeCurl($httpUrl, 2, $httpData);
//        var_dump($res);
////        if ($res['code'] < 0) {
////            return $this->toJson(-2, $res['msg']);
////        }
////        $res = $res['data'];
////        if ($res['code'] < 0) {
////            return $this->toJson(-2, $res['msg']);
////        }
////        return $this->toJson(0, '', $res['data']);
//    }

    //保存语音文本
    public function xfset()
    {
        $chat_id = $this->request->param('chat_id', 0);
        $msg = $this->request->param('msg', '');
        $res = $this->obj()->xfSet($chat_id, $msg);
        if (!$res) {
            return $this->toJson(-2, 'fail');
        }
        return $this->toJson();
    }

    //获取语音文本
    public function xfget()
    {
        $res = $this->obj()->xfGet();
        if (!$res) {
            return $this->toJson(-2, 'fail');
        }
        return $this->toJson();
    }

    //获取对话
    public function hhget()
    {
        $res = $this->obj()->hhGet();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //获取智能体答复
    public function botOne()
    {
        $hh_id = $this->request->param('hh_id', '7453276182402957312');
        $chat_id = $this->request->param('chat_id', '7454160295838236713');
        $res = $this->obj()->queOne();
        if (!$res) {
            return $this->toJson(-2, '没有用户询问');
        }
        $msgid = $res['id'];
        //发问题给智能体
        $httpUrl = 'https://api.coze.cn/v1/conversation/message/create?conversation_id='.$hh_id;
        $httpData = json_encode([
            'role' => 'user',
            'content' => '天气怎么样',
            'content_type' => 'text',
        ]);
        $res = $this->cozeCurl($httpUrl, 2, $httpData);
//        var_dump($res);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        //获取智能体回复
        $httpUrl = 'https://api.coze.cn/v3/chat/message/list?conversation_id='.$hh_id.'&chat_id='.$chat_id;
        $res = $this->cozeCurl($httpUrl);
//        var_dump($res);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $total = count($res['data']);
        if (!$total) {
            return $this->toJson(-2, '没有回复');
        }
        $msg = $res['data'][$total-1]['content'];
        $res = $this->obj()->queSet($msgid, $chat_id, $msg);
        if ($res['code'] < 0) {
            return $this->toJson(-2, '没有回复');
        }
        return $this->toJson(0, '', $msg);
    }

    /**
     * 构建CURL请求
     * @param string $url 请求地址
     * @param int $method 1get，2post
     * @param string $sring 请求数据
     */
    public function cozeCurl($url, $method = 1, $string = '')
    {
        $headers = $this->headers();
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        if ($method == 2) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=> -1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}